import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  Req,
  Query,
  NotFoundException,
  Request
} from '@nestjs/common';
import { VideoHistoryService } from './video-history.service';
import {
  PaginatedHistoryDto,
  VideoHistoryItemDto,
} from './dto/view-history.dto';
import { ApiOperation } from '@nestjs/swagger';

@Controller('video-history')
export class VideoHistoryController {
  constructor(private readonly videoHistoryService: VideoHistoryService) {}
  @Get('history')
  @ApiOperation({ summary: '分页获取用户浏览历史' })
  async getVideoHistory(
    @Req() req,
    @Query('page') page: number = 1,
    @Query('limit') limit: number = 10,
  ): Promise<PaginatedHistoryDto> {
    const userId = req.user.id;
    const { data, total } = await this.videoHistoryService.getPaginatedHistory(
      userId,
      page,
      limit,
    );
  
    return {
      items: data.map(VideoHistoryItemDto.fromEntity),
      total,
      currentPage: page,
      totalPages: Math.ceil(total / limit),
    };
  }

  @Delete('clearById/:id')
  @ApiOperation({ summary: '删除单个浏览历史' })
  async deleteHistoryItem(@Param('id') id: number, @Request() req) {
    const userId = req.user.id;
    // 验证记录是否存在且属于当前用户
    const record = await this.videoHistoryService.findOneByIdAndUser(
      id,
      userId,
    );
    if (!record) {
      throw new NotFoundException('记录不存在或无权删除');
    }
    await this.videoHistoryService.deleteById(id);
    return { success: true, message: '记录删除成功' };
  }

  @Delete('clear')
  @ApiOperation({ summary: '清空浏览历史' })
  async clearAllHistory(@Request() req) {
    const userId = req.user.id; // 从请求中获取用户ID
    await this.videoHistoryService.clearUserHistory(userId);
    return {
      success: true,
      message: '浏览历史已全部清空',
    };
  }

  @Post(':videoId')
  @ApiOperation({ summary: '新增浏览记录' })
  async create(@Param('videoId') videoId: number,  @Request() req) {
    const userId = req.user.id;
    await this.videoHistoryService.create(userId, Number(videoId));
    return { success: true, message: '浏览记录创建成功' };
  }
}
